﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using LeoGemini.Service.Infrastructure.Handler.Exception;
using Volo.Abp.Domain.Entities;

namespace GiftWishService.Domain.Aggregate.WishCart
{
    /// <summary>
    /// 心愿单聚合根
    /// </summary>
    [Table("tb_wish_cart")]
    public class WishCart : AggregateRoot<Guid>
    {
        /// <summary>
        /// ORM框架使用
        /// </summary>
        protected WishCart()
        {
            
        }

        public WishCart(Guid id)
        {
            Id = id;
            Items = new List<WishItem>();
        }
        
        public WishCart(Guid id, Guid referenceUserId) : this(id)
        {
            ReferenceUserId = referenceUserId;
        }
        
        /// <summary>
        /// 所属用户id
        /// </summary>
        [Column("reference_user_id")]
        public virtual Guid ReferenceUserId { get; private set; }
        
        /// <summary>
        /// 礼品袋条目
        /// </summary>
        [Column("items")]
        public virtual ICollection<WishItem> Items { get; private set; }

        /// <summary>
        /// 添加心愿单条目
        /// </summary>
        public void AddWishItem(string goodsId)
        {
            // 条目已存在
            if (Items.Any(w => w.GoodsId == goodsId))
                throw new ConflictException(ErrorMessage.CART_ITEM_ALREADY_EXISTS);
            
            Items.Add(new WishItem
            {
                GoodsId = goodsId
            });
        }
        
        /// <summary>
        /// 移除心愿单条目
        /// </summary>
        public void RemoveWishItem(string goodsId)
        {
            var item = Items.First(w => w.GoodsId == goodsId);
            
            // 条目不存在
            if (item == null)
                throw new NotFoundException(ErrorMessage.CART_ITEM_NOT_EXISTS);

            Items.Remove(item);
        }
    }
}